<template>
  <a-spin :spinning="loadingState.isLoad">
    <div class="SignInfo-container">
      <title-name title="签字信息"></title-name>
      <a-form-model
        ref="ruleForm"
        :model="formInfo"
        :rules="rules"
      >
        <a-row :gutter="24">
          <!-- <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="签字码"
              :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
              :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
              prop="pwdBase64"
            >
              <BaseInput
                :disabled="pageType === 'look'"
                placeholder="请输入签字码"
                v-model="formInfo.pwdBase64"
              />
            </a-form-model-item>
          </a-col> -->
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="签字图片"
              :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
              :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
              prop="imgBase64"
            >
              <div
                class="img-wrapper"
                v-if="pageType === 'look'"
              >
                <img
                  v-if="formInfo.imgBase64"
                  class="sign-img"
                  :src="formInfo.imgBase64"
                  alt="加载失败"
                  @click="visibleState.isPreview = true"
                >
              </div>
              <div v-else-if="$route.meta.isPim">
                <img
                  v-if="formInfo.imgBase64"
                  class="sign-img"
                  :src="formInfo.imgBase64"
                  alt="加载失败"
                  @click="visibleState.isPreview = true"
                >
                <a-upload
                  class="sign-upload"
                  accept="image/png,image/jpg,image/jpeg"
                  :show-upload-list="false"
                  :before-upload="beforeUpload"
                  @change="handleImageChangePim"
                >
                  <a-button
                    type="primary"
                    :loading="loading"
                  >重新上传</a-button>
                </a-upload>
              </div>
              <a-upload
                v-else
                name="file"
                accept="image/png,image/jpg,image/jpeg"
                list-type="picture-card"
                :file-list="fileList"
                :before-upload="beforeUpload"
                @change="handleImageChange"
                @preview="visibleState.isPreview = true"
              >
                <div v-if="fileList.length < 1">
                  <a-icon type="plus" />
                  <div class="ant-upload-text">上传</div>
                </div>
              </a-upload>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <BaseModal
        :visible="visibleState.isPreview"
        width="800px"
        @cancel="visibleState.isPreview = false"
        :footer="null"
      >
        <div class="preview-img-wrapper">
          <img
            class="img"
            :src="formInfo.imgBase64"
            alt="加载失败"
          />
        </div>
      </BaseModal>
    </div>
  </a-spin>
</template>

<script>
import BaseModal from '@/components/BaseModal'
import UploadList from '@/components/UploadList'
import { getSignInfoByUser, addSignInfo, updateSignInfo, deleteSignInfo } from '@/api/system/menuAndAuth.js'
function dataURLtoFile(dataurl, filename) {
  try {
    let arr = dataurl && dataurl.split(','),
      mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]),
      n = bstr.length,
      u8arr = new Uint8Array(n)
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n)
    }
    return new File([u8arr], filename, { type: mime })
  } catch (e) {
    console.error(e)
    return ''
  }
}
export default {
  name: 'SignInfo',
  components: {
    BaseModal
  },
  props: {
    pageType: {
      type: String,
      default: 'add'
    },
    userId: {
      type: String,
      default: ''
    },
    commonData: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      originInfo: null,
      formInfo: {
        imgBase64: ''
      },
      visibleState: {
        isPreview: false
      },
      loadingState: {
        isLoad: false
      },
      rules: {
        // pwdBase64: [{ required: true, message: '请输入', trigger: 'change' }]
      },
      fileList: [],
      // 签字图标loading
      loading: false
    }
  },
  computed: {
    realUserId() {
      return this.userId || this.commonData.userId
    }
  },
  created() {
    this.getSignInfoByUserReq()
  },
  methods: {
    beforeUpload(file) {
      const isLimitSize = file.size / 1024 <= 100
      if (!isLimitSize) {
        this.$message.error('图片必须小于100KB!')
        this.$nextTick(() => {
          if (!this.$route.meta.isPim) {
            this.fileList = []
            this.formInfo.imgBase64 = ''
          }
        })
      }
      return false
    },
    handleImageChange(info) {
      this.fileList = info.fileList
      if (this.fileList.length > 0) {
        const file = this.fileList[0].originFileObj
        // 转为base64
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = (ev) => {
          this.formInfo.imgBase64 = ev.target.result
          console.log(this.formInfo.imgBase6)
        }
      } else {
        this.formInfo.imgBase64 = ''
      }
    },
    handleSubmit(...args) {
      const [resolve, reject, options] = args
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) {
          reject && reject()
          return
        }
        try {
          if (options && options.isTab) {
            resolve && resolve()
            return
          }
          const { pwdBase64, imgBase64 } = this.formInfo
          const formData = new FormData()
          // 如果没有上传文件，就将base64转为文件，发送给服务器
          const file = (this.fileList[0] && this.fileList[0].originFileObj) || dataURLtoFile(imgBase64, 'upload.png')
          formData.append('signImg', file)
          let useDelete = false
          // 签字码和图片都没有的情况
          if (!pwdBase64 && !file) {
            // 如果有id，说明已存在数据，需要调删除接口清除签字信息(将删除标识置为true)
            if (this.formInfo.id) {
              useDelete = true
            } else {
              // 否则，说明是新增时提交空数据，此时不调接口
              this.$message.success('提交成功')
              resolve && resolve()
              return
            }
          }
          //  else if (!pwdBase64 || !file) {
          //   // 如果两者只传了一个，不允许提交
          //   this.$message.warning('签字码和签字图片必须一起提交')
          //   reject && reject()
          //   return
          // }
          const params = {
            params: {
              userId: this.realUserId,
              pwd: this.realUserId,
              id: this.formInfo.id || void 0
            },
            data: formData
          }
          let res = {}
          // 调用删除接口
          if (useDelete) {
            res = await deleteSignInfo({
              id: this.formInfo.id
            })
          } else {
            const fn = this.formInfo.id ? updateSignInfo : addSignInfo
            res = await fn(params)
          }
          this.formInfo = res.data || {}
          // 后台返回的base64需要添加头部信息
          this.formInfo.imgBase64 = 'data:image/png;base64,' + this.formInfo.imgBase64
          this.$message.success('提交成功')
          resolve && resolve()
        } catch (e) {
          console.error(e)
          reject && reject()
        }
      })
    },
    async getSignInfoByUserReq() {
      if (!this.realUserId) return
      try {
        if (this.loadingState.isLoad) return
        this.loadingState.isLoad = true
        const params = {
          userId: this.realUserId
        }
        const res = await getSignInfoByUser(params)
        this.formInfo = res.data || {}
        // 后台返回的base64需要添加头部信息
        if (this.formInfo.imgBase64) {
          this.formInfo.imgBase64 = 'data:image/png;base64,' + this.formInfo.imgBase64
          this.fileList.push({
            uid: '-1',
            name: 'upload.png',
            status: 'done',
            url: this.formInfo.imgBase64
          })
        }
      } catch (e) {
        console.error(e)
      } finally {
        this.loadingState.isLoad = false
      }
    },
    filterEditModel(type) {
      let flag = ''
      switch (type) {
        case 'add':
          flag = 2
          break
        case 'edit':
          flag = 1
          break
        case 'look':
          flag = 0
          break
        default:
          flag = 0
          break
      }
      return flag
    },
    /**
     * @description: 接管文件上传
     * @param {object} info 文件对象
     * @return {void}
     */
    async handleImageChangePim(info) {
      const isLimitSize = info.file.size / 1024 > 100
      if (isLimitSize) return
      this.loading = true
      const reader = new FileReader()
      reader.readAsDataURL(info.file)
      reader.onload = (ev) => {
        this.formInfo.imgBase64 = ev.target.result
      }
      if (info.file) {
        try {
          const formData = new FormData()
          formData.append('signImg', info.file)
          const params = {
            params: {
              userId: this.realUserId,
              pwd: this.realUserId,
              id: this.formInfo.id || void 0
            },
            data: formData
          }
          const fn = this.formInfo.id ? updateSignInfo : addSignInfo
          const res = await fn(params)
          if (res.code === 200) {
            this.$message.success('上传成功')
          }
        } catch (error) {
          console.error(error)
        } finally {
          this.loading = false
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
.SignInfo-container {
  .sign-img {
    width: 100px;
    height: 100px;
    object-fit: cover;
    cursor: pointer;
  }
  .sign-img-wrapper {
    position: relative;
    width: 126px;
    .icons {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      .icon {
        margin-right: 15px;
      }
    }
  }
}
.preview-img-wrapper {
  width: 100%;
  height: 100%;
  padding: 10px;
  .img {
    width: 100%;
    height: calc(var(--heightVh) * 0.6);
    object-fit: contain;
  }
}
.sign-upload {
  margin-left: 20px;
}
</style>